let numInput = document.querySelector(".num-input");
let upper = document.querySelector("#option1");
let lower = document.querySelector("#option2");
let num = document.querySelector("#option3");
let symbol = document.querySelector("#option4");
let flag = [false, false, false, false];
let btn = document.querySelector(".btn");
let pwd = document.querySelector(".pwd");
let copy = document.querySelector(".copy");
let cnt = 0;
let upperArray = [];

// 定义一个函数，随机弹出一个数并将其从列表中删除
function popRandomNumber(list) {
  // 如果没有元素了，返回 null
  if (list.length === 0) {
    return null;
  }

  // 随机选择一个索引
  let randomIndex = Math.floor(Math.random() * list.length);

  // 弹出并返回该索引对应的元素
  let poppedNumber = list.splice(randomIndex, 1)[0];

  return poppedNumber;
}
btn.addEventListener("click", () => {
  let arr = [];
  let idx2 = 0;
  let remain = 0;
  let res = "";
  cnt = 0;
  let len = numInput.value;
  flag[0] = upper.checked;
  flag[1] = lower.checked;
  flag[2] = num.checked;
  flag[3] = symbol.checked;
  flag.forEach((bol) => {
    cnt = bol ? cnt + 1 : cnt;
  });
  let key = parseInt(len / cnt);
  remain = len % cnt;
  flag.forEach((bol, idx) => {
    if (bol) {
      let out = key;
      if (idx2 < remain) {
        out += 1;
      }
      if (idx === 0) {
        for (let i = 0; i < out; i++) {
          let asciiCode = Math.floor(Math.random() * 26) + 65;

          // 返回对应的字母
          arr.push(String.fromCharCode(asciiCode));
        }
      } else if (idx === 1) {
        for (let i = 0; i < out; i++) {
          let asciiCode = Math.floor(Math.random() * 26) + 97;

          // 返回对应的字母
          arr.push(String.fromCharCode(asciiCode));
        }
      } else if (idx === 2) {
        for (let i = 0; i < out; i++) {
          let asciiCode = Math.floor(Math.random() * 10);

          // 返回对应的字母
          arr.push(asciiCode);
        }
      } else {
        for (let i = 0; i < out; i++) {
          let randomSymbol = getRandomSymbol();
          arr.push(randomSymbol);
        }
      }
      idx2++;
    }
  });
  while (arr.length > 0) {
    let randomNumber = popRandomNumber(arr);
    res += randomNumber;
  }
  pwd.textContent = res;
  // 选择 textarea 中的文本
});
copy.addEventListener("click", () => {
  navigator.clipboard
    .writeText(pwd.textContent)
    .then(() => {
      alert("文本已复制到剪贴板");
    })
    .catch((err) => {
      console.error("复制失败：", err);
    });
});

// 生成随机符号的函数
function getRandomSymbol() {
  // 定义符号的 ASCII 码范围
  const symbolRanges = [
    { min: 33, max: 47 },
    { min: 58, max: 64 },
    { min: 91, max: 96 },
    { min: 123, max: 126 },
  ];

  // 随机选择一个范围
  let randomRange =
    symbolRanges[Math.floor(Math.random() * symbolRanges.length)];

  // 在该范围内随机生成一个 ASCII 码
  let asciiCode =
    Math.floor(Math.random() * (randomRange.max - randomRange.min + 1)) +
    randomRange.min;

  // 返回对应的符号
  return String.fromCharCode(asciiCode);
}
